<?php

namespace app\common\model;

use houdunwang\crypt\Crypt;
use think\Loader;
use think\Model;
use think\Validate;

class Admin extends Model {
    protected $pk    = 'admin_id'; // 主键
    protected $table = 'blog_admin';

    public function login($data) {
        // 1.执行验证
        $validate = Loader::validate('Admin');
        // 如查验证不通过
        if (!$validate->check($data)) {
            return ['valid' => 0, 'msg' => $validate->getError()];
        }
        // 2.比对用户名和密码是否正确
        $pwd      = Crypt::encrypt($data['admin_pwd']);
        $userInfo = $this->where('admin_username', $data['admin_username'])->where('admin_pwd', $pwd)->find();
        if (is_null($userInfo)) {
            // 说明在数据库未匹配到相关的数据
            return ['valid' => 0, 'msg' => '用户名或密码不正确！'];
        }
        // 3.将用户信息存入到session中
        session('admin.admin_id', $userInfo['admin_id']);
        session('admin.admin_username', $userInfo['admin_username']);
        return ['valid' => 1, 'msg' => '登陆成功！'];
    }

    // 修改密码
    public function pass($data) {
        //1.执行验证
        $validate = new Validate([
            'admin_pwd'   => 'require',
            'new_pwd'     => 'require',
            'confirm_pwd' => 'require|confirm:new_pwd'
        ], [
            'admin_pwd.require'   => '请输入原始密码！',
            'new_pwd.require'     => '请输入新密码！',
            'confirm_pwd.require' => '请输入确认密码！',
            'confirm_pwd.confirm' => '两次密码不一致！'
        ]);
        if (!$validate->check($data)) {
            return ['valid' => 0, 'msg' => $validate->getError()];
        }
        //2.原始密码是否正确
        $pwd = Crypt::encrypt($data['admin_pwd']);
        $userInfo = $this->where('admin_id',session('admin.admin_id'))->where('admin_pwd',$pwd)->find();
        if(!$userInfo){
            return ['valid' => 0, 'msg' => '原始密码输入有误！'];
        }
        //3.修改保存新密码
        $rs = $userInfo->save([
           'admin_pwd' => Crypt::encrypt($data['new_pwd'])
        ]);
        if ($rs){
            return ['valid' => 1, 'msg' => '密码修改成功！'];
        }else{
            return ['valid' => 0, 'msg' => '密码修改失败！'];
        }
    }

}
